package org.example.dbcompare.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.dbcompare.model.ColumnInfo;

import javax.sql.DataSource;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author wuyong
 * @date 2025/10/22
 */
@Slf4j
public class CompareUtils {
    /**
     * 获取资源目录路径
     * 优先使用项目根目录下的resources目录，如果不存在则使用当前classpath
     * @return 资源目录路径
     */
    public static String getResourceDirectoryPath() {
        try {
            // 尝试获取项目根目录下的resources目录
            String projectRoot = System.getProperty("user.dir");
            String resourcesPath = projectRoot + "/src/main/resources";

            // 检查resources目录是否存在
            if (FileUtil.exist(resourcesPath)) {
                return resourcesPath;
            }

            // 如果resources目录不存在，尝试创建
            FileUtil.mkdir(resourcesPath);
            return resourcesPath;

        } catch (Exception e) {
            log.warn("无法获取项目resources目录，使用当前classpath: {}", e.getMessage());
            // 回退到使用当前classpath
            return ResourceUtil.getResource("").getPath();
        }
    }
    public static String getFullPath(String path,String configName){
        File configFile = FileUtil.file(CompareUtils.getResourceDirectoryPath(),path, configName);
        FileUtil.mkdir(configFile);
        return configFile.getAbsolutePath();
    }
    /**
     * 智能路径拼接：首路径为绝对路径则直接拼接，否则放入资源文件目录下
     * @param paths 多个目录和（文件）名
     * @return 完整路径
     */
    public static String joinPath(String... paths) {
        if (paths == null || paths.length == 0) {
            throw new IllegalArgumentException("路径参数不能为空");
        }
        String first = paths[0];
        // 判断首路径是否为绝对路径
        boolean isAbsolute = false;
        if (first != null && !first.isEmpty()) {
            Path testPath = Paths.get(first);
            isAbsolute = testPath.isAbsolute();
            // 兼容Windows下如c:, d:作为绝对路径
            if (!isAbsolute && first.length() > 1 && first.charAt(1) == ':') {
                isAbsolute = true;
            }
        }
        Path path;
        if (isAbsolute) {
            path = Paths.get(first, java.util.Arrays.copyOfRange(paths, 1, paths.length));
        } else {
            String resRoot = getResourceDirectoryPath();
            path = Paths.get(resRoot, paths);
        }
        return path.toString();
    }
    /**
     * 拼接路径，并自动在文件名扩展名前加上时间后缀（yyyyMMdd_HHmmss）
     * 逻辑同joinPath，但路径最后一段会补时间戳
     * @param paths 多个目录和（文件）名
     * @return 含时间戳的完整路径
     */
    public static String joinPathInsertTimestamp(String... paths) {
        if (paths == null || paths.length == 0) {
            throw new IllegalArgumentException("路径参数不能为空");
        }
        String first = paths[0];
        boolean isAbsolute = false;
        if (first != null && !first.isEmpty()) {
            Path testPath = Paths.get(first);
            isAbsolute = testPath.isAbsolute();
            if (!isAbsolute && first.length() > 1 && first.charAt(1) == ':') {
                isAbsolute = true;
            }
        }
        // 拆分文件名和其它路径
        String[] prefixPaths;
        String fileName;
        if (paths.length == 1) {
            prefixPaths = new String[0];
            fileName = paths[0];
        } else {
            prefixPaths = java.util.Arrays.copyOf(paths, paths.length - 1);
            fileName = paths[paths.length - 1];
        }
        // 生成时间戳后缀
        String timeSuffix = java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String finalFileName;
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            finalFileName = fileName.substring(0, dotIndex) + "_" + timeSuffix + fileName.substring(dotIndex);
        } else {
            finalFileName = fileName + "_" + timeSuffix;
        }
        Path path;
        if (isAbsolute) {
            // 注意: 拼接prefixPaths+finalFileName
            String[] joined = new String[prefixPaths.length + 1];
            System.arraycopy(prefixPaths, 0, joined, 0, prefixPaths.length);
            joined[joined.length - 1] = finalFileName;
            path = Paths.get(first, joined);
        } else {
            String resRoot = getResourceDirectoryPath();
            String[] joined = new String[prefixPaths.length + 1];
            System.arraycopy(prefixPaths, 0, joined, 0, prefixPaths.length);
            joined[joined.length - 1] = finalFileName;
            path = Paths.get(resRoot, first);
            if (joined.length > 1) {
                path = path.resolve(Paths.get("", java.util.Arrays.copyOfRange(joined, 1, joined.length)));
            }
        }
        return path.toString();
    }
    public static ColumnInfo getColumnMeta(DataSource dataSource, String tableName, String columnName)  {
        try {
            Connection conn = dataSource.getConnection();
            String catalog=conn.getCatalog();
            String schema = conn.getSchema();
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet rs = metaData.getColumns(catalog, schema, tableName, columnName);
            ColumnInfo columnInfo = new ColumnInfo(tableName,rs);
            return columnInfo;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}
